from flask import Blueprint, request, jsonify, current_app, render_template
from flask_login import login_required, current_user
from datetime import datetime, timedelta
from sqlalchemy.exc import SQLAlchemyError
from ..services.book_service import BookService
from ..extensions import BookNotAvailableError, NotFoundError,db
from ..models import BorrowRequest,BorrowRecord
import json
bp = Blueprint('book', __name__, url_prefix='/book')


@bp.route('/search', methods=['GET'])
def search():
    """搜索书籍"""
    try:
        query = request.args.get('query', '').strip()
        if not query:
            return jsonify({"success": False, "message": "请输入搜索内容"}), 400

        results = BookService.search_books(query)
        return jsonify({
            "success": True,
            "data": [{
                "id": book.id,
                "title": book.title,
                "author": book.author,
                "cover_image": book.cover_image,
                "status": "available" if book.is_available() else "unavailable"
            } for book in results]
        })
    except Exception as e:
        current_app.logger.error(f"搜索失败: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": "搜索服务不可用"}), 500


@bp.route('/books', methods=['GET'])
def api_get_books():
    """获取所有书籍列表"""
    try:
        books = BookService.get_all_books()

        # 调试日志
        current_app.logger.debug(f"获取到书籍数量: {len(books)}")
        if not books:
            current_app.logger.warning("数据库中没有书籍记录")

        # 构建响应数据时添加类型检查
        book_list = []
        for book in books:
            if not hasattr(book, 'is_available'):
                current_app.logger.error(f"Book对象缺少is_available方法: {book}")
                continue

            book_data = {
                "id": book.id,
                "title": book.title,
                "author": book.author,
                "cover_image": book.cover_image or "",
                "available": book.is_available(),
                "available_copies": book.available_copies,
                "total_copies": book.total_copies,
                "category": book.category or "",
                "isbn": book.isbn or ""
            }
            book_list.append(book_data)

        return jsonify({
            "success": True,
            "count": len(book_list),
            "data": book_list
        })

    except SQLAlchemyError as e:
        current_app.logger.error(f"数据库查询失败: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "message": "数据库查询失败",
            "data": []
        }), 500

    except Exception as e:
        current_app.logger.error(f"未知错误: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "message": "服务器错误",
            "data": []
        }), 500


@bp.route('/books/<int:book_id>', methods=['GET'])
def api_get_book(book_id):
    """获取单个书籍详情并跳转到详情页面"""

    book = BookService.get_book_by_id(book_id)
    return render_template('book_detail.html',
            book={
                "id": book.id,
                "title": book.title,
                "author": book.author,
                "description": book.description,
                "isbn": book.isbn,
                "category": book.category,
                "status": "available" if book.is_available() else "unavailable",
                "available_copies": book.available_copies,
                "total_copies": book.total_copies,
                "cover_image": book.cover_image
            }
        )


@bp.route('/borrow', methods=['POST'])
@login_required
def borrow():
    try:
        data = request.get_json()
        if not data or 'bookId' not in data:
            return jsonify({"success": False, "message": "缺少必要参数"}), 400

        # 调试：打印接收到的数据
        print(f"收到借阅申请数据：{data}")

        # 创建借阅申请记录
        new_request = BorrowRequest(  # 确保使用正确的模型类
            book_id=data['bookId'],
            user_id=current_user.id,
            status='pending',
            request_time=datetime.utcnow(),
            notes=json.dumps({
                'borrow_name': data.get('name'),
                'borrow_time': data.get('borrowTime'),
                'return_time': data.get('returnTime'),
                'class_name': data.get('className'),
                'student_id': data.get('studentId')
            })
        )

        db.session.add(new_request)
        db.session.commit()

        # 立即验证是否保存成功
        saved = BorrowRequest.query.get(new_request.id)
        print(f"已保存申请：ID={saved.id}, Status={saved.status}, Notes={saved.notes}")

        return jsonify({"success": True, "message": "借阅申请已提交"})

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"提交失败: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": "提交失败"}), 500


@bp.route('/return', methods=['POST'])
@login_required
def return_book():
    """归还书籍"""
    try:
        data = request.get_json()
        if not data or 'recordId' not in data:
            return jsonify({"success": False, "message": "缺少必要参数"}), 400

        BookService.return_book(data['recordId'])
        return jsonify({"success": True, "message": "归还成功"})
    except NotFoundError as e:
        return jsonify({"success": False, "message": str(e)}), 404
    except Exception as e:
        current_app.logger.error(f"归还失败: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": "归还失败"}), 500


# 路由文件修改 (book.py)
@bp.route('/return/request', methods=['POST'])
@login_required
def request_return():
    try:
        data = request.get_json()
        if not data or 'recordId' not in data:
            return jsonify({"success": False, "message": "参数错误"}), 400

        # 调试日志
        current_app.logger.debug(
            f"开始处理归还申请，记录ID:{data['recordId']}"
        )

        request_id = BookService.request_return(
            record_id=data['recordId'],
            user_id=current_user.id
        )

        # 必须立即刷新记录状态
        borrow_record = BorrowRecord.query.get(data['recordId'])
        return jsonify({
            "success": True,
            "message": "归还申请已提交",
            "status": borrow_record.status  # 返回最新状态
        })

    except Exception as e:
        current_app.logger.error(f"归还申请错误: {str(e)}")
        return jsonify({"success": False, "message": str(e)}), 400

@bp.route('/return/requests', methods=['GET'])
@login_required
def get_return_requests():
    """获取还书申请列表（管理员）"""
    try:
        if not current_user.is_admin:
            return jsonify({"success": False, "message": "权限不足"}), 403

        status = request.args.get('status', 'pending')
        requests = BookService.get_return_requests(status)

        return jsonify({
            "success": True,
            "data": requests
        })
    except Exception as e:
        current_app.logger.error(f"获取还书申请失败: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": "获取还书申请失败"}), 500


@bp.route('/return/process', methods=['POST'])
@login_required
def process_return():
    """处理还书申请（管理员）"""
    try:
        if not current_user.is_admin:
            return jsonify({"success": False, "message": "权限不足"}), 403

        data = request.get_json()
        if not data or 'requestId' not in data or 'action' not in data:
            return jsonify({"success": False, "message": "缺少必要参数"}), 400

        BookService.process_return_request(
            request_id=data['requestId'],
            admin_id=current_user.id,
            approve=data['action'] == 'approve',
            notes=data.get('notes')
        )

        return jsonify({
            "success": True,
            "message": "处理成功"
        })
    except NotFoundError as e:
        return jsonify({"success": False, "message": str(e)}), 404
    except Exception as e:
        current_app.logger.error(f"处理还书申请失败: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": "处理还书申请失败"}), 500


@bp.route('/renew', methods=['POST'])
@login_required
def renew_book():
    """续借书籍"""
    try:
        data = request.get_json()
        if not data or 'recordId' not in data:
            return jsonify({"success": False, "message": "缺少必要参数"}), 400

        result = BookService.renew_book(
            record_id=data['recordId'],
            renew_days=data.get('days', 14)
        )

        return jsonify({
            "success": True,
            "data": {
                "newDueDate": result.isoformat(),
                "message": "续借成功"
            }
        })
    except BookNotAvailableError as e:
        return jsonify({"success": False, "message": str(e)}), 400
    except Exception as e:
        current_app.logger.error(f"续借失败: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": "续借失败"}), 500
@bp.route('/borrowed', methods=['GET'])
@login_required
def get_borrowed_books():
    """获取借阅记录"""
    try:
        user_id = None if current_user.is_admin else current_user.id
        records = BookService.get_borrowed_books(user_id)

        return jsonify({
            "success": True,
            "data": records
        })
    except Exception as e:
        current_app.logger.error(f"获取借阅记录失败: {str(e)}", exc_info=True)
        return jsonify({"success": False, "message": "获取借阅记录失败"}), 500
